package com.fsds.crem.web.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fsds.crem.core.constant.Globals;
import com.fsds.crem.core.feature.orm.mybatis.Page;
import com.fsds.crem.core.util.ExceptionUtil;
import com.fsds.crem.core.util.LogUtil;
import com.fsds.crem.web.entity.TimeTaskLog;
import com.fsds.crem.web.service.TimeTaskLogService;
import com.fsds.crem.web.timetask.ReportTimeTask;

@Controller
@RequestMapping("/timetask")
public class TimeTaskController {

	private Logger logger = Logger.getLogger(TimeTaskController.class);
	
	@Resource
	private TimeTaskLogService timeTaskLogService;
	
	/**
	 * 初始化进入日终日结界面
	 * 
	 * @return
	 */
	@RequestMapping(value="/list")
	public String list(HttpServletRequest request,TimeTaskLog log,String pageNo){
		
		int pageNoInt = 1;
		
		if (pageNo != null && !"".equals(pageNo) ) {
			
				// 页码是数字的验证在前台处理
				pageNoInt = Integer.parseInt(pageNo); 
		}
		
		Page<TimeTaskLog> page = new Page<TimeTaskLog>(pageNoInt);
		
		List<TimeTaskLog> logList = timeTaskLogService.findByPage(log, page).getResult();
		
		request.setAttribute("logList", logList);
		request.setAttribute("page", page);
		
		return "timetask/manualtask";
	}
	
	/**
	 * 重跑批次
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/rerun")
	@ResponseBody
	public String rerun(HttpServletRequest request,HttpServletResponse response){
		
		JSONObject json = new JSONObject();
		
		String dateStr = request.getParameter("date");
		
		TimeTaskLog log = new TimeTaskLog();
		
		try {
		
			if(StringUtils.isNotEmpty(dateStr)){
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
				Date date = sdf.parse(dateStr);
				
				log.setCreateDate(date);
				log.setBeginTime(new Date());
				log.setReportName("销售报表"+new SimpleDateFormat("yyyyMMdd").format(date));
				
				new ReportTimeTask().run(date,"totalJob_rerun.kjb");
				log.setState(Globals.TIME_TASK_RUN_SUCCESS);
				log.setContent("批次执行成功");
				json.put("result", "success");
			}
			else{
				
				json.put("result", "date_error");
			}
		
		} catch (Exception e) {
			log.setState(Globals.TIME_TASK_RUN_FAIL);
			log.setContent("异常信息："+ExceptionUtil.getExceptionMessage(e));
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			json.put("result", "fail");
			
		} finally {
			
			log.setEndTime(new Date());
			timeTaskLogService.saveTimeTaskLog(log);
		}
		
		return json.toString();
	}
	
	/**
	 * 根据时间段运行批次
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/manualRun")
	@ResponseBody
	public String manualRun(HttpServletRequest request,HttpServletResponse response){
		
		JSONObject json = new JSONObject();
		
		String beginDateStr = request.getParameter("beginDate");
		String endDateStr = request.getParameter("endDate");
		
		if(StringUtils.isNotEmpty(beginDateStr) && StringUtils.isNotEmpty(endDateStr)){
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			
			Calendar calendar = Calendar.getInstance();
			Date endDate = null;
			
			try {
				
				calendar.setTime(sdf.parse(beginDateStr));
				endDate = sdf.parse(endDateStr);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			ReportTimeTask reportTimeTask = new ReportTimeTask();
			
			boolean flag = true;
			
			while(calendar.getTime().before(endDate)){
				
				// 批次日志信息
				TimeTaskLog log = new TimeTaskLog();
				
				try {
					
					// 当前日期
					Calendar c = Calendar.getInstance();
			        c.setTime(new Date());
					log.setCreateDate(calendar.getTime());
					log.setReportName("销售报表"+new SimpleDateFormat("yyyyMMdd").format(calendar.getTime()));
					log.setBeginTime(c.getTime());
					
					// 执行报表批次
					reportTimeTask.run(calendar.getTime(),"totalJob.kjb");
					log.setState(Globals.TIME_TASK_RUN_SUCCESS);
					log.setContent("批次执行成功");
				} catch (Exception e) {
					
					flag = false;
					log.setState(Globals.TIME_TASK_RUN_FAIL);
					log.setContent("异常信息："+ExceptionUtil.getExceptionMessage(e));
					e.printStackTrace();
					LogUtil.error(e.getMessage(), e);
				} finally {
					
					log.setEndTime(new Date());
					
					// 记录批次日志信息
					timeTaskLogService.saveTimeTaskLog(log);
				}
				
				// 日期加一天
				calendar.add(Calendar.DAY_OF_MONTH, 1);
			}
			
			if(flag){
				json.put("result", "success");
			}
			else{
				json.put("result", "fail");
			}
		}
		else{
			
			json.put("result", "date_error");
		}
		
		return json.toString();
	}
}
